package net.sudot.chess.business.controller.web;

import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import net.sudot.chess.business.wechat.api.WechatApiService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * 微信对接入口
 *
 * @author tangjialin on 2018-03-01
 */
@Controller
@RequestMapping("/wechat/server")
public class WechatServerController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final boolean debugEnabled = logger.isDebugEnabled();

    @Resource
    private WechatApiService wechatApiService;
    @Resource
    private WxMpMessageRouter router;

    /**
     * 微信服务器认证接口
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return 认证通过原样返回echostr内容, 否则返回"非法请求"
     */
    @ResponseBody
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {
        if (debugEnabled) { logger.debug("接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr); }
        if (StringUtils.isAnyBlank(signature, timestamp, nonce)
                || !wechatApiService.checkSignature(timestamp, nonce, signature)) {
            logger.warn("微信服务器对接接口收到非法请求的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
            return "非法请求";
        }
        return echostr;
    }

    /**
     * 微信服务器信息通知接口
     *
     * @param requestBody  信息正文
     * @param signature    微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param encType      加密内心
     * @param msgSignature 加密内容签名
     * @param timestamp    时间戳
     * @param nonce        随机数
     * @return 返回响应信息
     */
    @ResponseBody
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@RequestBody(required = false) String requestBody,
                       @RequestParam(name = "signature", required = false) String signature,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature,
                       @RequestParam(name = "timestamp", required = false) String timestamp,
                       @RequestParam(name = "nonce", required = false) String nonce) {
        if (debugEnabled) {
            logger.debug("接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                    signature, encType, msgSignature, timestamp, nonce, requestBody);
        }

        if (StringUtils.isAnyBlank(signature, timestamp, nonce)
                || !wechatApiService.checkSignature(timestamp, nonce, signature)) {
            logger.warn("微信服务器对接接口收到非法请求,请求数据:[signature=[{}], encType=[{}], msgSignature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                    signature, encType, msgSignature, timestamp, nonce, requestBody);
            return "非法请求";
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = router.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equals(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody,
                    wechatApiService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
            if (debugEnabled) { logger.debug("消息解密后内容为：{} ", inMessage.toString()); }
            WxMpXmlOutMessage outMessage = router.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wechatApiService.getWxMpConfigStorage());
        }
        if (debugEnabled) { logger.debug("微信回复信息：\n{}", out); }
        return out;
    }
}
